package com.nifostasky.comic.common.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ShellUtil {
    /**
     * 获取系统是windows还是linux;
     * @return windows 返回 true,
     *         linux 返回 false
     */
    public static Boolean getOs(){
        Properties props=System.getProperties(); //获得系统属性集
        String osName = props.getProperty("os.name"); //操作系统名称
        if(osName.toLowerCase().contains("linux")){
//            return "/bin/sh -c";
            return false;
        }else if(osName.toLowerCase().contains("windows")){
//            return "cmd /c";
            return true;
        }else{
            throw new RuntimeException("服务器不是linux|windows操作系统");
        }
    }

    /**
     * 获取python文件中的结果(已处理)
     * @param commands 命令集合
     * @param outEncode 输出编码  java -> shell
     * @param inEncode 输入编码 shell -> java
     * @return
     */
    public static String pyInteractive(List<String> commands,String outEncode,String inEncode){
        String result = null;
        String originalResult = ShellUtil.interactive(commands,outEncode,inEncode);
        System.out.println("python执行结果: " + originalResult);
        System.out.println("传参: " + commands.toString());
        if (Objects.isNull(originalResult))
            return null;
        String patternStr = "```(.*?)```";
        // 创建 Pattern 对象
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(originalResult);
        if (matcher.find()) {
            result = matcher.group(0);
            result = result.substring(3,result.length()-3);
        }
        return result;
    }

    /**
     * 获取命令输出结果
     * @param commands 命令集合
     * @param outEncode 输出编码  java -> shell
     * @param inEncode 输入编码 shell -> java
     * @return
     */
    public static String interactive(List<String> commands,String outEncode,String inEncode) {
        StringBuilder result = new StringBuilder();
        try {
            //获取第一个命令,并移除
            String init = commands.get(0);
            commands.remove(0);
            //执行命令类
            Process finalProcess = Runtime.getRuntime().exec(init);
            // 执行命令
            Thread thread1 = ShellUtil.executeCommandThread(commands, finalProcess,outEncode);
            thread1.start();
            // 获取执行的命令结果内容;标准错误输出 和 标准输出
            Thread thread2 = ShellUtil.getStandardOutput(result, finalProcess,inEncode);
            thread2.start();
            Thread thread3 = ShellUtil.getErrorOutput(result, finalProcess,inEncode);
            thread3.start();
            // 等待程序执行完毕
            thread1.join();
            thread2.join();
            thread3.join();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 执行命令进程
     * @param commands 命令
     * @param finalProcess 管道
     * @param outEncode 输出编码  java -> shell
     * @return
     */
    private static Thread executeCommandThread(List<String> commands,Process finalProcess,String outEncode){
        Thread thread1 = new Thread(() -> {
            //保存输入的命令
            BufferedWriter writer = null;
            //重置数据
            Scanner scanner = new Scanner(System.in);
            try {
                for (String command : commands) {
                    //将输入内容 输出到 命令窗口中;
                    writer = new BufferedWriter(new OutputStreamWriter(finalProcess.getOutputStream(),outEncode));
                    writer.write(command);
                    writer.newLine();
                    writer.flush();
                }

            }catch (Exception e){
                e.printStackTrace();
            }
            //关闭输出流
            try {
                if (Objects.nonNull(writer))
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return thread1;
    }

    /**
     * 获取标准输出
     * @param result 返回值
     * @param finalProcess
     * @param inEncode 输入编码 shell -> java
     * @return
     */
    private static Thread getStandardOutput(StringBuilder result,Process finalProcess,String inEncode){
        Thread thread2 = new Thread(() -> {
            try{
                //输出控制台中显示的内容
                BufferedReader br = new BufferedReader(new InputStreamReader(finalProcess.getInputStream(),inEncode));
                String cmdout = "";
                while ((cmdout = br.readLine()) != null) {
                        result.append(cmdout + "\n");
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        });
        return thread2;
    }

    /**
     * 获取错误输出
     * @param result 返回值
     * @param finalProcess 管道
     * @param inEncode 输入编码 shell -> java
     * @return
     */
    private static Thread getErrorOutput(StringBuilder result,Process finalProcess,String inEncode){
        Thread thread3 = new Thread(() -> {
            try{
                //输出控制台中显示的内容
                BufferedReader br = new BufferedReader(new InputStreamReader(finalProcess.getErrorStream(),inEncode));
                String cmdout = "";
                while ((cmdout = br.readLine()) != null) {
                        result.append(cmdout + "\n");
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        });
        return thread3;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("\n"+"=======================================================================================================================");
        //{"GB2312","UTF-8","GB18030","ISO-8859-1","ISO-8859-2","GBK"};
        String baseurl2 = "https://manhua.dmzj.com/putonggongjishiquantigongjierqienengercigongjidema";
        String baseurl1 = "https://manhua.dmzj.com/putonggongjishiquantigongjierqienengercigongjidema/64616.shtml";
        String function1 = "python -u -c \"import sys ; import io ; import manhua_dmzj_com as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.indexComic())\"";
        String function2 = "python -u -c \"import sys ; import io ; import manhua_dmzj_com as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; keyword = '你' ; print(comic.keywordSearch(keyword,1))\"";
        String function3 = "python -u -c \"import sys ; import io ; import manhua_dmzj_com as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.chapterInfoComic('"+ baseurl2 +"'))\"";
        String function4 = "python -u -c \"import sys ; import io ; import manhua_dmzj_com as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.pictureInfoComic('"+ baseurl1 +"'))\"";
        List<String> strs = new ArrayList<>();
        strs.add("cmd");
//        strs.add("E:");
//        strs.add("cd E:\\java\\python");
        strs.add("F:");
        strs.add("cd F:\\staticResource\\comic_spider\\python");
//        strs.add(new String(function2.getBytes("GBK")));
//        String sysEncode = JsonUtil.getEncoding(function2);
//        System.out.println(sysEncode);
        String function2s = new String(function2.getBytes("utf-8"), "utf-8");
        strs.add(function2s);
        System.out.println("-------------------------");
//        String str = ShellUtil.interactive(strs,"GBK");
        String str1 = ShellUtil.pyInteractive(strs,"GBK","utf-8");
//        System.out.println(str);
        System.out.println(str1);
        System.out.println("======================================================================================================================="+"\n");
    }
}
